﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;

namespace XZTZ.UMP.WEB.Pages.Flow.FlowBusiness
{

    public class AppSetting
    {

        private static readonly object objLock = new object();
        private static AppSetting instance = null;

        private IConfigurationRoot Config { get; }

        private AppSetting()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            Config = builder.Build();
        }

        public static AppSetting GetInstance()
        {
            if (instance == null)
            {
                lock (objLock)
                {
                    if (instance == null)
                    {
                        instance = new AppSetting();
                    }
                }
            }
            return instance;
        }

        public static string GetConfig(string name)
        {
            return GetInstance().Config.GetSection(name).Value;

        }
        
        public static DataTable GetStepListByFlowID(Guid guidFlowID, Guid guidCurrentStepID)
        {
            string strConn = FlowBusiness.AppSetting.GetConfig("ConnectionStrings:DefaultConnection");
            
            SqlConnection cn = new SqlConnection(strConn);

            SqlParameter[] cmdParms = new SqlParameter[] { new SqlParameter("@guidFlowID", SqlDbType.UniqueIdentifier), new SqlParameter("@guidCurrentStepID", SqlDbType.UniqueIdentifier) };
            cmdParms[0].Value = guidFlowID;
            cmdParms[1].Value = guidCurrentStepID;
            string cmdText = "select *,b.strStepTypeName,isnull(c.strStepName,'---') strPreviousStepName,isnull(d.strStepName,'---') strNextStepName from Flow_TemplateStep a inner join Base_SignatureStepType b on a.strStepTypeID = b.strStepTypeID left join Flow_TemplateStep c on a.guidPreviousStep = c.guidFlowStepID left join Flow_TemplateStep d on a.guidNextStep = d.guidFlowStepID where a.guidFlowID=@guidFlowID And a.guidFlowStepID <> @guidCurrentStepID order by a.intIndexNo";
            SqlCommand cmd = new SqlCommand(cmdText, cn);
            cmd.Parameters.AddRange(cmdParms);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataTable dataTable = new DataTable();
            adapter.Fill(dataTable);
            cmd.Parameters.Clear();
            cmd.Dispose();
            return dataTable;
        }

    }
}
